package me.yuzho.study.concurrency.java8;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;

/** The interface ReadWriteLock specifies another type of lock maintaining a pair of locks for read and write access.
 *  The idea behind read-write locks is that it's usually safe to read mutable variables concurrently 
 *  as long as nobody is writing to this variable.
 *  So the read-lock can be held simultaneously by multiple threads 
 *  as long as no threads hold the write-lock. 
 *  This can improve performance and throughput in case that reads are more frequent than writes.
 *  
 *  当没有线程持有写锁时，读锁可以被多个线程同时持有，同时读某一个变量是安全的
 * @author yzhou-citrix
 *
 */
public class Lock2ReadWriteLock {
    
    private static void testReadWriteLock() {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Map<String, String> map = new HashMap<>();

        ReadWriteLock lock = new ReentrantReadWriteLock();

        executor.submit(() -> {
            lock.writeLock().lock();
            try {
                System.out.println("In writting: " + Thread.currentThread().getName() + ","  + System.nanoTime());
                ConcurrentUtils.sleep(1);
                map.put("foo", "bar");
                System.out.println("In writting: " + Thread.currentThread().getName() + ","  + System.nanoTime());
            } finally {
                lock.writeLock().unlock();
            }
        });

        
        Runnable readTask = () -> {
            lock.readLock().lock();
            try {
                System.out.println("In reading: " + Thread.currentThread().getName() + "," + System.nanoTime());
                System.out.println(map.get("foo"));
                ConcurrentUtils.sleep(1);
            } finally {
                lock.readLock().unlock();
            }
        };
        executor.submit(readTask);
        executor.submit(readTask);

        ConcurrentUtils.stop(executor);
    }
    
    /** java 8 ships with a new kind of lock called StampedLock which also support read and write locks 
     * just like in the example above. 
     * In contrast to ReadWriteLock the locking methods of a StampedLock return a stamp 
     * represented by a long value. 
     * You can use these stamps to either release a lock or to check if the lock is still valid. 
     * Additionally stamped locks support another lock mode called optimistic locking.
     * StampeLock 与ReadWriteLock类似
     * 
     */
    private static void testStampedLock() {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Map<String, String> map = new HashMap<>();

        StampedLock lock = new StampedLock();

        executor.submit(() -> {
            long stamp = lock.writeLock();
            try {
                System.out.println("StampLock writting: " + Thread.currentThread().getName() + ","  + System.nanoTime());
                ConcurrentUtils.sleep(1);
                map.put("foo", "bar");
            } finally {
                lock.unlockWrite(stamp);
            }
        });

        Runnable readTask = () -> {
            long stamp = lock.readLock();
            try {
                System.out.println("StampLoc reading: " + Thread.currentThread().getName() + ","  + System.nanoTime());
                System.out.println(map.get("foo"));
                ConcurrentUtils.sleep(1);
            } finally {
                lock.unlockRead(stamp);
            }
        };
        executor.submit(readTask);
        executor.submit(readTask);

        ConcurrentUtils.stop(executor);
    }
    
    private static void testOptimisticLock() {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        StampedLock lock = new StampedLock();

        executor.submit(() -> {
            long stamp = lock.tryOptimisticRead();
            try {
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                ConcurrentUtils.sleep(1);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                ConcurrentUtils.sleep(2);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
            } finally {
                lock.unlock(stamp);
            }
        });

        executor.submit(() -> {
            long stamp = lock.writeLock();
            try {
                System.out.println("Write Lock acquired");
                ConcurrentUtils.sleep(2);
            } finally {
                lock.unlock(stamp);
                System.out.println("Write done");
            }
        });

        ConcurrentUtils.stop(executor);
    }

    public static void main(String[] args) {
        //testReadWriteLock();
        //testStampedLock();
        testOptimisticLock();
    }
}
